const Service = require('egg').Service;

const _ = require('lodash')

class AppService extends Service {
    //获取角色权限
    async getPower(id) {
        const { app: { model: { Role, RolePower } } } = this
        const data = RolePower.findAll({
            attributes: [['power_text', 'label'], ['power_code', 'code']],
            include: [{
                attributes: [],
                model: Role,
                require: true,
                where: {
                    id
                }
            }],
            raw: true,
        })
        return data
    }

    //保存角色权限
    async savePower({ id, powers }) {
        const { app: { model: { Role, RolePower } } } = this
        await RolePower.destroy({
            where: {
                role_id: id
            }
        })
        var powers = _.map(powers, t => {
            return {
                power_text: t.label,
                power_code: t.code,
                role_id: id
            }
        })
        return await RolePower.bulkCreate(powers)
    }
}
return AppService

module.exports = AppService